//
//  MainPageViewController.swift
//  DollarBuy
//
//  Created by 郑东喜 on 2016/11/6.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  首页轮播图

import UIKit
import WebKit


class MainPageViewController : UIViewController,WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate,ShareVCDelegate {

    
    //分享变量
    var titleStr : String = ""
    var desc : String = ""
    var link : String = ""
    var imgURL : String = ""
    
    var viewController = ShareViewController()
    
    var webView: WKWebView!
    
    //全局链接变量
    var url : String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        self.navigationItem.title = "一元云购"
        
        //配置webview
        let configuration = WKWebViewConfiguration()
        let userContentController = WKUserContentController()
        
        
        //添加交互条目
        //分享到微信
        userContentController.add(self as WKScriptMessageHandler, name: "shareWeixinInfo")
        //微信支付
        userContentController.add(self as WKScriptMessageHandler, name: "weixinPay")
        
        configuration.userContentController = userContentController
        
        // 设置偏好设置
        let preferences = WKPreferences()
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        preferences.javaScriptCanOpenWindowsAutomatically = true
        preferences.minimumFontSize = 10.0
        configuration.preferences = preferences
        
        configuration.processPool = WKProcessPool()
        webView = WKWebView.init(frame: view.bounds, configuration: configuration)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self

        
        if mainIndexArray.count > 1 {
            let urlStr = mainIndexArray.lastObject
            
            webView.load(URLRequest.init(url: URL.init(string: urlStr as! String)!))
        } else {
            DispatchQueue.main.async {
                //http://www.163.com/
                //                let url = URL.init(string: "http://www.163.com/")
                let url = URL.init(string: "http://yungou.ie1e.com/app/index.aspx?devtype=1")

                self.webView.load(URLRequest.init(url: url!))
            }
        }
        
        //本地加载
//        let htmlPath = Bundle.main.path(forResource: "WKWebViewMessageHandler", ofType: "html")
//        
//        DispatchQueue.main.async {
//            do {
//                let fileURL = try NSString.init(contentsOfFile: htmlPath!, encoding: String.Encoding.utf8.rawValue)
//                let baseURL = NSURL.fileURL(withPath: htmlPath! as String)
//                webView.loadHTMLString(fileURL as String, baseURL: baseURL)
//            } catch  {
//                
//            }
//        }
//        
        view.addSubview(webView)
        
    }
    
    /**
     *  JS 调用 swift 时 webview 会调用此方法
     *
     *  @param userContentController  webview中配置的userContentController 信息
     *  @param message                JS执行传递的消息
     */
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
        let msg = message.name
        
        //将获取到的数据解析成字典
        let messageDic = message.body as! NSDictionary
        
        print(messageDic)
        
        
        if  msg == "shareWeixinInfo" {
            print("shareWeixinInfo")
            
            
            //解析取回的字典数据
            titleStr = messageDic["title"] as! String
            desc = messageDic["desc"] as! String
            link = messageDic["link"] as! String
            imgURL = messageDic["imgUrl"] as! String
            

            viewController = ShareViewController()
            viewController.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
            viewController.delegate = self
            self.present(viewController, animated: true, completion: nil)
            
        }else if msg == "weixinPay" {
            print("weixinPay")
            
            let urlString = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=ios"
            
            postWithPath(path: urlString, paras: nil, success: { (response) in
                //判读返回值是否为空
                guard let dic = response as? NSDictionary else {
                    return
                }
                
                print(dic)
                
                WXTool.shared.sendWXPay(wxDict: dic)
                
                
            }) { (error) in
                print(error.localizedDescription)
            }
            
            
            let artController = UIAlertController(title: "支付", message: message.body as? String, preferredStyle: .alert)
            
            artController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))

        }
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        url = (navigationAction.request.url?.absoluteString)!
        
        print(url)
        
        print(mainIndexArray.count)
        
        if navigationAction.navigationType == WKNavigationType.linkActivated {
            
            //如果为本身或者本身携带#的url进行自身刷新。
            if url == "http://yungou.ie1e.com/app/index.aspx" || url == "http://yungou.ie1e.com/app/index.aspx#" {

                self.webView.load(URLRequest.init(url: URL.init(string: url)!))
                
                mainIndexArray.removeAllObjects()
                
            } else {
                print(mainIndexArray)
                mainIndexArray.add(url)
                aaa(str: mainIndexArray.lastObject as! String)
            }

            decisionHandler(.cancel)
            
        } else {
            decisionHandler(.allow)
        }
    }
    
    //url---
    func aaa(str : String) -> Void {
        
        let vvv = MainPageViewReplaceVIew()
        vvv.url = str
        self.navigationController?.pushViewController(vvv, animated: true)
        
    }
    
    //获取标题
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.navigationItem.title = self.webView.title
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    

}

extension MainPageViewController {
    func shareType(__data: Int) {
        
        viewController.dismiss(animated: true, completion: nil)
        
        
        switch __data {
        case 100:
            print("QQ 好友")
            QQTool.shared.qqShare(title: titleStr, desc: desc, link: link, imgUrl: imgURL, type: QQApiURLTargetTypeAudio)
        case 101:
            print("QQ 空间")
            QQTool.shared.qqShare(title: titleStr, desc: desc, link: link, imgUrl: imgURL, type: QQApiURLTargetTypeAudio)
        case 102:
            print("朋友圈")
            
            print(titleStr)
            WXTool.shared.shareText(title: titleStr, desc:desc, link: link, imgUrl: imgURL, shareType: 1)
        case 103:
            print("微信好友")
            WXTool.shared.shareText(title: titleStr, desc:desc, link: link, imgUrl: imgURL, shareType: 0)
        default:
            break
        }
        
    }
}

